<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
define('NOSESSION',true);
define('TC_API',true);
require_once '../core/core.php';
if($_AR['close']){
	exi('站点已关闭','error');
}
set_exi(function($message,$type,$action,$url){
	ob_clean();
	if($type=='error'){
		
		exit('');
	}else{
		$message=ijson_encode($message);
		exit($message);
	}
	
});
if(!$_GET['signature'] || !$_GET['timestamp'] || !$_GET['eventId']){
	
	exi('error1','error');
}
if($TIMESTAMP-$_GET['timestamp']>30){
	exi('error2','error');
}
//校验签名
$setting=core_setting('tecent_cloud');
$setting['token']='oNyvVWjt2pGrihehJ6p4uxeJwsre';
if(!$setting['token']){
	exi('error3','error');
}
$check=array($setting['token'],(string)$_GET['timestamp'],(string)$_GET['eventId']);
sort($check,SORT_STRING);
$string=implode('',$check);
$signature=hash('sha256',$string);
if($signature !=$_GET['signature']){
	exi('error4','error');
}
$postdata=file_get_contents('php://input');
if(!$postdata){
	exi('error5','error');
}
$postdata=json_decode($postdata,true);
if(!$postdata || !$postdata['action']){
	exi('error6','error');
}
if($postdata['action']=='verifyInterface'){
	//接口校验
	$res=array(
		'echoback'=>$postdata['echoback'],
	);
	exi($res);
}
if($postdata['action']=='createInstance'){
	//实例创建通知
	$product_id=intval($postdata['productId']);
	$group=pdo_get('core_account_group',array('tc_product_id'=>$product_id));
	if(!$group){
		exi('找不到相应套餐！','error');
	}
	if(!$postdata['openId']){
		exi('缺少用户openid，实例创建失败！','error');
	}
	//检查用户是否存在
	$uniacid=pdo_getcolumn('core_open_user',array('open_uid'=>$postdata['openId']),'uniacid');
	if($uniacid){
		$update=array(
			'groupid'=>$group['id'],
		);
		if($group['days']){
			$update['endtime']=TIMESTAMP+$group['days']*86400;
		}
		pdo_update('core_accounts',$update,array('uniacid'=>$uniacid));
		
	}else{
		//创建用户
		do{
			$username='qcloud_'.random(5,true);
			$check=pdo_getcolumn('core_users',array('name'=>$username),'id');
		}while($check);
		$new_member=array(
			'name'=>$username,
			'password'=>random(8),
			'groupid'=>$group['id'],
		);
		if($postdata['mobile']){
			$new_member['mobile']=$postdata['mobile'];
		}
		$uniacid=cfc('user')->create_user($new_member);
		$user=array(
			'uniacid'=>$uniacid,
			'open_id'=>'1003',//1003表示来自腾讯云开放平台的用户
			'open_uid'=>$openid,
		);
		pdo_insert('core_open_user',$user);
	}
	$res=array(
		'signId'=>$uniacid,
		'appInfo'=>array(
			'website'=>SITEROOT,
			'authUrl'=>SITEROOT.'manage/index.php?core/user.login/qcloud_login',
		),
		'additionalInfo'=>array(
			array('name'=>'登陆网址','value'=>SITEROOT),
			array('name'=>'用户名','value'=>$username),
			array('name'=>'初始密码','value'=>$new_member['password']),
			
		),
	);
	exi($res);
}